package esp.store.imp;

import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;

import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.ukpass.util.FilePathUtil;

import esp.store.dao.StoreClientDao;

/** This Class is design to finish download and upload file **/
public class StoreClientDaoFastDFSImp implements StoreClientDao {
	static esp.basic.log.ESPLogger logger = esp.basic.log.ESPLogger.getLogger(StoreClientDaoFastDFSImp.class.getName());

	private static String conf_filename = FilePathUtil.getSDCardPath()
			+ "/ESP_NISK/fdfs_client.conf";;
	private static TrackerClient tracker;

	public StoreClientDaoFastDFSImp() {
		super();
		
		try {
			ClientGlobal.init(conf_filename);
			tracker = new TrackerClient();
		} catch (Exception e) {
			logger.error("ClientGlobal init error\t", e);
		}
	}

	/** Do Operate DownLoadFile **/
	@Override
	public boolean DownloadFile(String downLoadXML, String toDirPath, int fileID) {
		StorageClient1 client;
		TrackerServer trackerServer;
		try {
			trackerServer = tracker.getConnection();
			client = new StorageClient1(trackerServer, null);
			int result = ParserXmlAndDownLoad(toDirPath, getRootElement(downLoadXML), client);
			if (result == 0) {
				trackerServer.close();
				return true;
			} else {
				trackerServer.close();
				throw new Exception();
			}
		} catch (Exception e) {
			logger.error("DownLoadFile error \t" + fileID);
			return false;
		}
	}

	/** Do Operate UploadFile **/
	@Override
	public String UploadFile(String sourceFileFullPath) {
		String serialID = null;
		StorageClient1 client;
		TrackerServer trackerServer;
		try {
			if (tracker==null)
				tracker=new TrackerClient();
			trackerServer= tracker.getConnection();
			client = new StorageClient1(trackerServer, null);
			serialID = client.upload_file1(sourceFileFullPath, null, null);
			trackerServer.close();
			return serialID;
		} catch (Exception e) {
			logger.error("---UploadFile---", e);
			return serialID;
		}
	}

	/** Do Operate parser xml and do download **/
	@SuppressWarnings("unchecked")
	public static int ParserXmlAndDownLoad(String downLoadPath, Element e, StorageClient1 client) {
		File file = new File(downLoadPath);
		if (!file.exists()) {
			file.mkdirs();
		}
		ArrayList<Object> attributeList = new ArrayList<Object>();
		for (Iterator<Attribute> ia = e.attributeIterator(); ia.hasNext();) {
			Attribute attribute = (Attribute) ia.next();
			attributeList.add(attribute.getData());
		}
		String fileName = (String) attributeList.get(0);

		int type = Integer.valueOf((String) attributeList.get(2));
		String externalID = (String) attributeList.get(3);
		String downLoadpath = downLoadPath + "/" + fileName;
		if (type == 2 && !externalID.equals("")) {
			try {
				int rs = client.download_file1(externalID, downLoadpath);
				if (rs != 0) {
					logger.info("download file " + downLoadpath + " fail" + externalID);
					return -1;
				}
			} catch (Exception e1) {
				logger.error("getxmlParser downloadfile error \t", e1);
				return -1;
			}
		} else if (type == 1) {
			File file1 = new File(downLoadpath);
			if (!file1.exists()) {
				file1.mkdirs();
			}
		}
		for (Iterator<Object> ie = e.elementIterator(); ie.hasNext();) {
			Element element = (Element) ie.next();
			String downLoadPath2 = downLoadPath + "/" + attributeList.get(0);
			ParserXmlAndDownLoad(downLoadPath2, element, client);
		}
		return 0;
	}

	/** Do Operate get the Xml RootElement **/
	public static Element getRootElement(String xml) {
		SAXReader saxReader = new SAXReader();
		Document document = null;
		try {
			document = saxReader.read(new StringReader(xml));
		} catch (Exception e) {
			logger.error("getXmlParser error \t", e);
		}
		return document.getRootElement();
	}
}
